package com.cat.model.common.util;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;

import org.apache.commons.lang.StringUtils;

import com.alonew.core.commons.tuple.TwoTuple;

public class ImageUtil {	
	public static String wrapImageUrl(String url){
		if(StringUtils.isEmpty(url)){
			return url;
		}
		
		if(url.startsWith("http://") || url.startsWith("https://")){
			return url;
		}
		
		if(url.startsWith("static/")){
			return StaticFileUtil.staticRootUrl() + url;
		}
		
		if(url.startsWith("/yami")){
			return "http://182.92.216.116/" + url;
		}
		
		if(url.startsWith("yami")){
			return "http://182.92.216.116/" + url;
		}
		
		return "http://182.92.216.116/yami/" + url;
	}
	
	public static String fixRichImageUrl(String richHtml){
		richHtml = richHtml.replace("src=\"http://weixin.yamichefs.com", "src=\"");
		richHtml = richHtml.replace("src=\"http://app.yamichefs.com", "src=\"");
		richHtml = richHtml.replace("src=\"/", "src=\"http://weixin.yamichefs.com/");
		
		return richHtml;
	}
	
	public static String wrapImagePath(String path){
		if(StringUtils.isEmpty(path)){
			return path;
		}
		
		if(path.startsWith("http://")){
			return path;
		}
		
		if(path.startsWith("static/")){
			return StaticFileUtil.staticRootPath() + path;
		}
		
		if(path.startsWith("/yami")){
			return "/root/data/www" + path;
		}
		
		if(path.startsWith("yami")){
			return "/root/data/www/" + path;
		}
		
		return "/root/data/www/yami/" + path;
	}
	
	/**
	 * 获取图片宽高比
	 * */
	public static BigDecimal getImageRatio(String path){
		int[] size = null;
		InputStream in = null;
		
		URL url = null;
		try {
			url = new URL(wrapImageUrl(path));
			in = url.openStream();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
//		System.out.println(wrapImageUrl(path));
		try {
//			in = new FileInputStream(wrapImagePath(path));
			in = url.openStream();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return new BigDecimal("1.5");
		} catch (IOException e) {
			e.printStackTrace();
			return new BigDecimal("1.5");
		}
		
		size = getWidthAndHeight(in);
		System.out.println("in" + in);
		System.err.println("size:" + size);
		if(null == size){
			return new BigDecimal("1.5");
		}
				
		float result = (float)size[0]/(float)size[1];
		return new BigDecimal(result).setScale(3, BigDecimal.ROUND_HALF_UP);
	}
	
	
	/**
	 * 
	 * */
	public static boolean doImageQuailty(File image, String targetPath, float d){
		BufferedInputStream bis = null;//获取一个上传文件的输入流   
		InputStream fis = null;	  
		ImageOutputStream outputStream = null;
		ImageWriter writer = null;
		
		try {
			bis = new BufferedInputStream(new FileInputStream(image));
			fis = new FileInputStream(image);
			BufferedImage bufferimage = javax.imageio.ImageIO.read(fis); // 构造Image对象
			
			
			ImageTypeSpecifier type = ImageTypeSpecifier
					.createFromRenderedImage(bufferimage);
			Iterator<ImageWriter> iter = ImageIO.getImageWriters(type, "jpg");
			if (iter.hasNext()) {
				writer = (ImageWriter) iter.next();
			}
			if (writer == null) {
				return false;
			}
			IIOImage iioImage = new IIOImage(bufferimage, null, null);
			ImageWriteParam param = writer.getDefaultWriteParam();

			param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);

			param.setCompressionQuality(d);
			
			try {
				outputStream = ImageIO.createImageOutputStream(new File(targetPath));
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
			writer.setOutput(outputStream);
			writer.write(null, iioImage, param);
			outputStream.flush();
			
			return true;
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}finally{
			try {
				outputStream.close();
				bis.close();
				fis.close();
				writer.dispose();
			} catch (IOException e) {
			}
		}
		return false;
	}
	
	
	/** 
     * 压缩图片 
     * @param sourcePath 源路径(包含图片) 
     * @param targetPath 目标路径 null则默认为源路径 
     * @param width 压缩后宽度 
     * @param height 压缩后高度 
     * @return 目标路径 
     * @throws IOException if sourcePath image does not exist 
     */  
    public static String compress(String sourcePath, String targetPath, int width, int height) throws IOException{  
        File imageFile = new File(sourcePath);  
        if(!imageFile.exists()){
            throw new IOException("Not found the images:"+sourcePath);  
        }
        
        if(targetPath==null || targetPath.isEmpty()){
        	targetPath = sourcePath;  
        }
        
        String format = sourcePath.substring(sourcePath.lastIndexOf(".")+1,sourcePath.length());  
        BufferedImage image = ImageIO.read(imageFile);  
        image = compress(image,width,height);  
        ImageIO.write(image, format, new File(targetPath));  
        return targetPath;  
    }
    
    /** 
     * 压缩图片 
     * @param sourceImage    待压缩图片 
     * @param width          压缩图片高度 
     * @param heigt          压缩图片宽度 
     */  
    private static BufferedImage compress(BufferedImage sourceImage, int width, int height){  
        BufferedImage zoomImage = new BufferedImage(width, height, sourceImage.getType());  
        Image image = sourceImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);  
        Graphics gc = zoomImage.getGraphics();  
        gc.setColor(Color.WHITE);  
        gc.drawImage(image , 0, 0, null);  
        return zoomImage;  
    }
	
	public static int[] getWidthAndHeight(File image){
		FileInputStream imgis = null;
		try {
			imgis = new FileInputStream(image);
		} catch (FileNotFoundException e) {
			return null;
		}
		BufferedImage src = null;
		try {
			src = javax.imageio.ImageIO.read(imgis);
		} catch (IOException e) {
			return null;
		}
		int srcWidth = src.getWidth(null); //得到源图宽
		int srcHeight = src.getHeight(null); //得到源图长
		
		return new int[]{srcWidth, srcHeight};
	}
	
	public static int[] getWidthAndHeight(InputStream is){
		
		BufferedImage src = null;
		try {
			src = javax.imageio.ImageIO.read(is);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		System.out.println("src:"+src);
		int srcWidth = src.getWidth(null); //得到源图宽
		int srcHeight = src.getHeight(null); //得到源图长
		
		return new int[]{srcWidth, srcHeight};
	}
	
	/**
	 * 保存业务图片
	 * */
	public static String saveBizImage(File image, String imageFileName) {
		String imagePath = StaticFileUtil.sysBizImageRelativePath() + FileUtil.buildDatePath();
		TwoTuple<String, byte[]> md5AndData = FileUtil.readAndCalMd5(image);
		FileUtil.writeFile(StaticFileUtil.staticRootPath() + imagePath, imageFileName, md5AndData.second);
		return imagePath + "/" + imageFileName;
	}
}
